import React, { FC, useEffect, useState } from 'react'
import './index.css'
import { Button, Checkbox, Col, message, Row, Select, Steps } from 'antd'
import { CheckCircleOutlined, CheckCircleTwoTone } from '@ant-design/icons';
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { useHistory } from "react-router";
import { getSecretString } from '@/utils/encrypt';

const { Step } = Steps
const { Option } = Select

const AchievementIssue: FC = () => {


    const [studentUserId, setStudentUserId] = useState<any>([])
    const [reviewerUserId, setReviewerUserId] = useState<any>([])
    const [context, setContext] = useState<any>([])
    const onChange = (value: any) => {

        setStudentUserId(value)
    }

    const onUserChange = (value: any) => {
        console.log(value)
        setReviewerUserId(value)
    }
    const onFileChange = (value: any) => {
        setContext(value)
    }


    const steps = [
        {
            title: '选择成绩文件',
            context: <AchievementFile onChange={onChange} onFileChange={onFileChange} />
        },
        {
            title: '审核人设置',
            context: <Reviewer onChange={onUserChange} />
        },
        {
            title: '完成',
            context: <AchievementSuccess />
        },
    ]


    const [current, setCurrent] = React.useState(0);

    const next = async () => {
        console.log(studentUserId)
        if (current === 0) {

            if (!studentUserId.length) {
                message.error('请选择接收人')
                return
            }
        }

        if (current === 1) {
            if (!reviewerUserId.length) {
                message.error('请选择审核人')
                return
            }
        }
        setCurrent(() => {
            if (current == 1) {
                console.log(studentUserId);

                run({ noticeType: 3, content: context, reviewerUserId, studentUserId: studentUserId.map((item: any) => getSecretString(`${item}`)) })
            }
            return current + 1
        });
    };
    const prev = () => {
        setCurrent(current - 1);
    };

    //敏感词信息提醒
    const { run } = useRequest((params) => fetchRequest(url.REVIEWER, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (!result.success) {
                message.error(result.errorMsg)
                return

            }
            if (result.success) {
                message.success(result.data)
            }
        }
    })

    const router = useHistory()


    return <div className={'achievement-issue'}>
        <div className="achievement-title">
            <Steps current={current}>
                {steps.map((item: any) => <Step key={item.title} title={item.title} />)}
            </Steps>
        </div>
        {steps.map((item: any, index) => <div key={item.title}
            className={`${current === index ? 'show' : 'hidden'}`}>{item.context}</div>)}


        <div className={'achievement-btn-wrap'}>
            {current < steps.length - 1 && (
                <Button type="primary" onClick={() => next()}>
                    下一步
                </Button>
            )}
            {current === 1 && (
                <Button style={{ margin: '0 8px' }} onClick={prev}>
                    上一步
                </Button>
            )}

            {current === 2 && (
                <Button onClick={() => router.go(0)} type="primary">
                    再发布一份
                </Button>
            )}

        </div>
    </div>
}

const AchievementFile: FC<{ onChange: (value: any) => void, onFileChange: (value: any) => void }> = ({
    onChange,
    onFileChange
}) => {


    //敏感词信息提醒
    const { data } = useRequest((params) => fetchRequest(url.GET_SCORE_LIST, params), {
        onSuccess: async (result, params) => {
            if (!result.success) {
                message.error(result.errorMsg)
                return

            } else {
            }
        }
    })

    /*文件*/
    const [scoreId, setScoreId] = useState<any>('')

    return <div className={'achievement-file'}>
        <Row>
            <Col span={12} offset={6}>
                <Row className={'achievement-file-context'}>
                    <Col span={2} className={'achievement-file-key'}>
                        成绩文件:
                    </Col>
                    <Col span={20} offset={2}>
                        <Select style={{ width: '100%' }} onChange={value => {
                            setScoreId(value);
                            onFileChange(value)
                        }}>
                            {data?.data?.map((item: any) => <Option value={item.id} key={item.id}>
                                {item.title}
                            </Option>)}
                        </Select>
                    </Col>
                </Row>
            </Col>
        </Row>
        <Row>
            <Col span={12} offset={6}>
                <Row className={'achievement-file-context'}>
                    <Col span={2} className={'achievement-file-key'}>
                        接收人:
                    </Col>
                    <Col span={20} offset={2}>
                        <StudentList scoreId={scoreId} onUserChange={onChange} />
                    </Col>
                </Row>
            </Col>
        </Row>
    </div>
}

const AchievementSuccess: FC = () => {
    return <div className={'achievement-success-wrap'}>
        <div className={'achievement-success'}>
            <CheckCircleTwoTone twoToneColor="#52c41a" className={'achievement-success-icon'} />
            <div className={'achievement-success-context'}>
                <h2>提交成功</h2>
                <span>请注意短信提醒</span>
            </div>
        </div>
    </div>
}

const Reviewer: FC<{ onChange: (value: any) => void }> = ({ onChange }) => {

    //敏感词信息提醒
    const { data } = useRequest(() => fetchRequest(url.GET_REVIEWER, {}), {
        onSuccess: async (result, params) => {
            if (!result.success) {
                message.error(result.errorMsg)
                return

            }
        }
    })


    return <div className={'achievement-file'}>
        <Row>
            <Col span={12} offset={6}>
                <Row className={'achievement-file-context'}>
                    <Col span={2} className={'achievement-file-key'}>
                        审核人:
                    </Col>
                    <Col span={20} offset={2}>
                        <Select style={{ width: '100%' }} mode="multiple" onChange={onChange}>
                            {data?.data?.map((item: any) => <Option value={item.userId}
                                key={item.userId}>{item.reviewerName}</Option>)}
                        </Select>
                    </Col>
                </Row>
            </Col>
        </Row>
    </div>
}


const StudentList: FC<{ scoreId: string, onUserChange: (value: any) => void }> = ({ scoreId, onUserChange }) => {

    //
    const { data, run } = useRequest((params) => fetchRequest(url.GET_SCORE_BY_STUDENT, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (!result.success) {
                message.error(result.errorMsg)
                return

            }
        }
    })

    const [indeterminate, setIndeterminate] = useState(false);
    const [checkAll, setCheckAll] = React.useState(false);

    /*智能学生证全选*/
    const [cardIndeterminate, setCardIndeterminate] = useState(false);
    const [cardCheckAll, setCardCheckAll] = React.useState(false);

    const [checkedList, setCheckedList] = React.useState([]);

    const onCheckAllChange = (e: any) => {
        setCheckedList(e.target.checked ? data?.data?.map((item: any) => item.userId) : [])

        onUserChange(e.target.checked ? data?.data?.map((item: any) => item.userId) : [])
        setIndeterminate(false);
        setCheckAll(e.target.checked);
        setCardCheckAll(e.target.checked);
    }

    const onChange = (list: any) => {
        setCheckedList(list);
        /*所选择科目item*/


        setIndeterminate(!!list.length && list.length < data?.data?.length);
        setCheckAll(list.length === data?.data?.length);

        const subList = data?.data?.filter((item: any) => list.includes(item.userId)).filter((item: any) => item.isSmartStudentCard === 1)
        const moreList = data?.data?.filter((item: any) => item.isSmartStudentCard === 1)
        setCardCheckAll(subList.length === moreList.length)


    }

    const onCardCheckAll = (e: any) => {
        const list = data?.data?.filter((item: any) => item.isSmartStudentCard === 1).map((item: any) => item.userId)
        const flag = e.target.checked
        setCardCheckAll(flag)
        if (checkAll) {
            if (flag) {
                // @ts-ignore
                setCheckedList([...data?.data?.map((item: any) => item.userId)])
            } else {
                setCheckedList(checkedList.filter(check => !list.includes(check)))
            }
        }

        if (!checkAll) {
            if (flag) {
                setCheckedList(list)
            } else {
                console.log(checkedList.filter(check => !list.includes(check)))
                setCheckedList(checkedList.filter(check => !list.includes(check)))
            }
        }


    }

    useEffect(() => {

        setIndeterminate(!!checkedList.length && checkedList.length < data?.data?.length);
        onUserChange(checkedList)

    }, [checkedList])


    useEffect(() => {
        if (scoreId) {
            run({ scoreId })
        }
    }, [scoreId])
    return <div className={'student-list'}>
        <Checkbox.Group onChange={onChange} value={checkedList}>
            <Row>
                {data?.data?.map((item: any) => <Col span={6} key={item.userId}>
                    <Checkbox
                        value={item.userId}>{item.studentName}({item.studentId})</Checkbox>
                </Col>)}
            </Row>
        </Checkbox.Group>
        <Row>
            {data?.data?.length > 0 ? <Col>
                <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange}
                    checked={checkAll}>
                    <span style={{ color: '#1890ff' }}>全选/取消</span>
                </Checkbox>

                <Checkbox indeterminate={cardIndeterminate} onChange={onCardCheckAll}
                    checked={cardCheckAll}>
                    <span style={{ color: '#1890ff' }}>智能学生证</span>
                </Checkbox>
            </Col> : null}
        </Row>
    </div>
}


export default AchievementIssue
